package com.sdkj.fixed.asset.system.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.sdkj.fixed.asset.api.system.in_vo.RegisterParam;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.RandomUtils;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.common.utils.mail.MailBean;
import com.sdkj.fixed.asset.common.utils.mail.MailConfig;
import com.sdkj.fixed.asset.common.utils.mail.MailUtils;
import com.sdkj.fixed.asset.pojo.system.*;
import com.sdkj.fixed.asset.system.mapper.RoleAndUserMapper;
import com.sdkj.fixed.asset.system.mapper.UsageManagementMapper;
import com.sdkj.fixed.asset.system.util.RedisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.mail.MessagingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author niuliwei
 * @description
 * @date 2021/4/8 13:23
 */
@Service
@Transactional
public class RegisterService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private OrgService orgService;
    @Autowired
    private UserService userService;
    @Autowired
    private UsageManagementMapper usageManagementMapper;
    @Autowired
    private RoleAndUserMapper roleAndUserMapper;

    @Value("${life.time}")
    private Integer lifeTime;
    @Value("${life.assets.num}")
    private String lifeAssetsNum;

    @Value("${email.sendemail}")
    private  String sendEmail;  // 邮件发送人的邮件地址
    @Value("${email.password}")
    private  String password;   //发件人的邮件授权码
    @Value("${email.sendserver}")
    private  String sendServer; // 发件服务器
    @Value("${email.port}")
    private  int port; // 端口
    /**
     * 注册
     * @param registerParam
     */
    public boolean register(RegisterParam registerParam) throws Exception {
        String userPassword = RandomUtils.randomLetAndNum(8);

        String code = String.valueOf(redisUtil.get(registerParam.getEmail()));
        if(StringUtil.isBlank(code) || "null".equals(code)){
            throw new LogicException("验证码已过期");
        }
        if(!code.equals(registerParam.getAuthCode())){
            throw new LogicException("验证码不正确");
        }

        //是否已经注册过
        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name",registerParam.getOrgName());
        List<OrgManagement> list = orgService.selectByExample(example);
        if(list.size() > 0 ){
            throw new LogicException("该公司已经被注册");
        }

        //新增公司
        String orgCodeNum = "";
        Example example1 = new Example(OrgManagement.class);
        Example.Criteria criteria1 = example1.createCriteria();
        List<OrgManagement> list1 = new ArrayList<>();
        do{
            orgCodeNum = RandomStringUtils.random(4, true, true);
            criteria1.andEqualTo("code", orgCodeNum);
            list1 = orgService.selectByExample(example1);
        } while (list1.size() > 0);

        OrgManagement orgManagement = new OrgManagement();
        orgManagement.setCode(orgCodeNum);
        orgManagement.setName(registerParam.getOrgName());
        orgManagement.setType(1);
        orgManagement.setCuser("注册");
        orgManagement.setEuser("注册");
        orgManagement.setCtime(DateUtil.now());
        orgManagement.setEtime(DateUtil.now());
        orgManagement.setState(1);
        orgManagement.setPid("NONE");
        orgManagement.setTreecode("");
        orgService.insertSelective(orgManagement);

        orgManagement.setTreecode(orgManagement.getId());
        orgService.updateByPrimaryKeySelective(orgManagement);

        //新增部门
        String deptCodeNum = "";
        do{
            deptCodeNum = RandomStringUtils.random(4, true, true);
            criteria1.andEqualTo("code", deptCodeNum);
            list1 = orgService.selectByExample(example1);
        } while (list1.size() > 0);
        OrgManagement deptManagement = new OrgManagement();
        deptManagement.setCode(deptCodeNum);
        deptManagement.setName("系统部门");
        deptManagement.setType(2);
        deptManagement.setCuser("注册");
        deptManagement.setEuser("注册");
        deptManagement.setCtime(DateUtil.now());
        deptManagement.setEtime(DateUtil.now());
        deptManagement.setState(1);
        deptManagement.setPid(orgManagement.getId());
        deptManagement.setTreecode("");
        orgService.insertSelective(deptManagement);

        deptManagement.setTreecode(orgManagement.getId()+","+deptManagement.getId());
        orgService.updateByPrimaryKeySelective(deptManagement);

        //新增用户
        UserManagement userManagement = new UserManagement();
        userManagement.setEmail(registerParam.getEmail());
        userManagement.setTel(registerParam.getTel());
        String userName = registerParam.getOrgName()+"管理员";
        if(userName.length()>16){
            userName = userName.substring(userName.length() -16);
        }
        userManagement.setName(userName);
        userManagement.setCuser("注册");
        userManagement.setEuser("注册");
        userManagement.setCtime(DateUtil.now());
        userManagement.setEtime(DateUtil.now());
        userManagement.setState(1);
        userManagement.setCompanyId(orgManagement.getId());
        userManagement.setDeptId(deptManagement.getId());
        userManagement.setType("1");
        userManagement.setIsOnJob("1");
        userManagement.setPassword(DigestUtils.md5Hex(userPassword));
        userManagement.setTopCompanyId(orgManagement.getId());
        userManagement.setEmployeeid(RandomStringUtils.random(4, false, true));
        userManagement.setDataIsAll(1);

        //手机号整库唯一//姓名唯一
        userService.validateTel(userManagement.getTel(), "");
        userService.validateName(userManagement.getName(), "", userManagement.getTopCompanyId());

        String employeeId = userService.createEmployeeId(userManagement);
        userManagement.setEmployeeid(employeeId);

        userService.insertSelective(userManagement);

        //新增公司使用情况
        UsageManagement usageManagement = new UsageManagement();
        usageManagement.setCompanyId(orgManagement.getId());
        usageManagement.setNumber(lifeAssetsNum);
        usageManagement.setType(1);
        usageManagement.setCuser(userManagement.getId());
        usageManagement.setEuser("注册");
        usageManagement.setCtime(DateUtil.now());
        usageManagement.setEtime(DateUtil.now());
        usageManagement.setDate(TimeTool.getBeforMonth(lifeTime).substring(0,10));
        usageManagementMapper.insertSelective(usageManagement);

        //初始化角色和菜单
        RoleManagement role = orgService.initRole("注册", orgManagement.getId());

        //管理员绑定角色
        RoleAndUser userAndRole = new RoleAndUser();
        userAndRole.setUserId(userManagement.getId());
        userAndRole.setRoleId(role.getId());
        roleAndUserMapper.insertSelective(userAndRole);


        //密码发送邮件
        MailBean mailBean = new MailBean();
        mailBean.setTitle("固定资产管理系统注册");
        mailBean.setToEmail(registerParam.getEmail());
        mailBean.setEmailMessage("固定资产管理系统\n" +
                "用户名：【"+registerParam.getTel()+"】\n" +
                "登录密码：【"+ userPassword +"】");
        MailConfig mailConfig = new MailConfig();
        mailConfig.setPassword(password);
        mailConfig.setPort(port);
        mailConfig.setSendEmail(sendEmail);
        mailConfig.setSendServer(sendServer);
        mailBean.setMailConfig(mailConfig);
        boolean b = MailUtils.sendMail(mailBean);
        return b;
    }

    /**
     * 获取验证码
     * @return
     */
    public boolean authCode(String email) throws MessagingException {
        String code = RandomStringUtils.random(4, false, true);
        //发送邮件
        MailBean mailBean = new MailBean();
        mailBean.setTitle("固定资产管理系统注册");
        mailBean.setToEmail(email);
        mailBean.setEmailMessage("固定资产管理系统注册验证码：【"+code+"】");
        MailConfig mailConfig = new MailConfig();
        mailConfig.setPassword(password);
        mailConfig.setPort(port);
        mailConfig.setSendEmail(sendEmail);
        mailConfig.setSendServer(sendServer);
        mailBean.setMailConfig(mailConfig);
        boolean b = MailUtils.sendMail(mailBean);
        if(b){
            //加到缓冲
            redisUtil.set(email, code, 60);
        }
        return b;
    }
}
